﻿using KJSyncXP.Extensions;
using KJSyncXP.Sqlite.Model;
using KJSyncXP.Views;
using log4net;
using log4net.Core;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Controls;

public class IdFileManager
{
    private readonly string _dataDirectory;
    private readonly string[] _templateLines;
    private readonly log4net.ILog _logger;
    private readonly AppConfig _config;
    // 关键字段在模板中的行索引（从0开始）
    public const int checiNumberIndex = 1;      // 车次
    public const int shiftIndex = 7;             // 班组
    public const int machineNumberIndex = 8;    // 机台号
    public const int lotNumberIndex = 9;      // 批号
    public const int mhStringIndex = 16;      // MH
    public const int tc30StringIndex = 19;      // TC30
    public const int tc90StringIndex = 20;      // TC90
    public const int userCodeIndex = 56;        // 工号


    public IdFileManager(ILog logger, AppConfig config)
    {
        _logger = logger;
        _config = config;
        _dataDirectory = _config.IdFileDataDirectory;
        // 确保数据目录存在
        if (!Directory.Exists(_dataDirectory))
        {
            Directory.CreateDirectory(_dataDirectory);
        }

        // 加载模板内容
        _templateLines = LoadTemplate();
    }

    /// <summary>
    /// 加载模板文件内容
    /// </summary>
    private string[] LoadTemplate()
    {
        string baseDir = AppDomain.CurrentDomain.BaseDirectory;

        string _templatePath = Path.Combine(baseDir, "template.ID");
        if (!File.Exists(_templatePath))
        {
            throw new FileNotFoundException("模板文件不存在", "Resources/template.ID");
        }

        return File.ReadAllLines(_templatePath);
    }


    /// <summary>
    /// 新增.id文件 若存在则覆盖(处理手动修改和自动修改标识，可能会会使用创建临时.lock文件)
    /// </summary>
    public bool CreateNewFile(string fileName, string checiNumber, string shift, string lotNumber,
        string machineNumber, string mhString, string tc30String, string tc90String,
        string userCode,List<Sqlite_KJ_TEST_STANDARD> MHList, List<Sqlite_KJ_TEST_STANDARD> TC30List, List<Sqlite_KJ_TEST_STANDARD> TC90List)
    {
        try {
            string newFilePath = Path.Combine(_dataDirectory, fileName + ".id");
            string lockFilePath = Path.Combine(_dataDirectory, fileName + ".lock"); //修改时判断是手动/MES
            string bakFilePath = Path.Combine(_dataDirectory, fileName + ".bak"); // 备份文件用于手动修改时记录上一次数据

            string[] newFileLines;

            //修改时不能直接覆盖，要先读取文件
            var isExist = FileExists(fileName + ".id");
            if (isExist)
            {
                // 文件存在，读取现有文件内容
                newFileLines = File.ReadAllLines(newFilePath);
            }
            else
            {
                // 文件不存在，使用模板内容
                newFileLines = (string[])_templateLines.Clone();
            }

            // 设置关键字段
            newFileLines[checiNumberIndex] = checiNumber;
            newFileLines[shiftIndex] = shift;
            newFileLines[machineNumberIndex] = machineNumber;
            newFileLines[lotNumberIndex] = lotNumber;
            newFileLines[mhStringIndex] = mhString;
            newFileLines[tc30StringIndex] = tc30String;
            newFileLines[tc90StringIndex] = tc90String;
            newFileLines[userCodeIndex] = userCode;

            // 保存新文件        
            File.WriteAllLines(lockFilePath, new string[0]);
            File.WriteAllLines(bakFilePath, newFileLines);
            File.WriteAllLines(newFilePath, newFileLines);
            return true;
        }
        catch (Exception ex)
        {
            _logger.Error($"保存文件失败：{ex.Message}");
            return false;
        }        
    }


    /// <summary>
    /// 检查.id文件是否存在
    /// </summary>
    public bool FileExists(string fileName)
    {
        string filePath = Path.Combine(_dataDirectory, fileName);
        return File.Exists(filePath);
    }

    /// <summary>
    /// 获取.id文件内容（用于查看）
    /// </summary>
    public string[] GetFileContent(string fileName)
    {
        string filePath = Path.Combine(_dataDirectory, fileName);

        if (File.Exists(filePath))
        {
            return File.ReadAllLines(filePath);
        }

        return null;
    }




    /*  /// <summary>
        /// 删除.id文件
        /// </summary>
        public bool DeleteFile(int id)
        {
            string filePath = Path.Combine(_dataDirectory, $"{id}.id");

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
                return true;
            }

            return false;
        }*/


}
